<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <title>智能推荐套餐</title>
    <!-- 引入 marked 和 github-markdown-css -->
    <script src="./js/marked.min.js"></script>
    <link rel="stylesheet" href="./css/github-markdown-light.css">
    <style>
        body {
            margin: 0;
            font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Helvetica, Arial, sans-serif;
            background-color: #f0f2f5;
        }
        #container {
            max-width: 900px;
            margin: 20px auto;
            padding: 20px;
            border-radius: 12px;
            background: #fafafa;
            box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
        }
        #msgDiv {
            height: 70vh;
            overflow-y: auto;
            padding: 20px;
            background: #ffffff;
            border-radius: 8px;
            display: flex;
            flex-direction: column;
            gap: 16px;
        }
        .markdown-body {
            box-sizing: border-box;
            min-width: 200px;
            max-width: 100%;
            margin: 0;
        }
        #ctrl {
            margin-top: 16px;
            display: flex;
            gap: 10px;
        }
        input[type="text"] {
            flex: 1;
            padding: 10px 12px;
            font-size: 14px;
            border: 1px solid #d9d9d9;
            border-radius: 6px;
            outline: none;
            transition: border-color 0.3s;
        }
        input[type="text"]:focus {
            border-color: #4096ff;
        }
        button {
            padding: 10px 20px;
            font-size: 14px;
            cursor: pointer;
            border: none;
            border-radius: 6px;
            transition: all 0.3s;
        }
        .btn-primary {
            background-color: #4096ff;
            color: white;
        }
        .btn-primary:hover:not(:disabled) {
            background-color: #3085ff;
        }
        .btn-secondary {
            background-color: #f0f0f0;
            color: #666;
        }
        .btn-secondary:hover:not(:disabled) {
            background-color: #e0e0e0;
        }
        button:disabled {
            opacity: 0.5;
            cursor: not-allowed;
        }
        .error {
            color: #ff4d4f;
            font-weight: bold;
        }
        /* 聊天消息样式 */
        .message-wrapper {
            display: flex;
            gap: 8px;
            max-width: 75%;
        }
        .message-wrapper.user {
            align-self: flex-end;
        }
        .message-wrapper.system {
            align-self: flex-start;
        }
        .message-avatar {
            width: 32px;
            height: 32px;
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 14px;
            font-weight: bold;
            color: white;
            flex-shrink: 0;
        }
        .message-avatar.user {
            background-color: #4096ff;
        }
        .message-avatar.system {
            background-color: #1890ff;
        }
        .message-content {
            padding: 12px 16px;
            border-radius: 12px;
            word-wrap: break-word;
        }
        .message-content.user {
            background-color: #4096ff;
            color: white;
        }
        .message-content.system {
            background-color: #f0f0f0;
            color: #333;
        }
        .message-content.markdown {
            white-space: pre-wrap;
        }
        .message-divider {
            text-align: center;
            color: #999;
            font-size: 12px;
            margin: 10px 0;
        }
        .message-divider span {
            background-color: #fff;
            padding: 0 10px;
        }
    </style>
</head>
<body>
<div id="container">
    <h2>智能推荐套餐</h2>

    <div id="msgDiv"><!-- 聊天消息会实时渲染到这里 --></div>

    <div id="ctrl">
        <input  id="question" type="text" placeholder="点击发送按钮发送消息" value="我叫小王，为我推荐合适的套餐。"/>
        <button id="sendBtn" class="btn-primary">发送</button>
        <button id="stopBtn" class="btn-secondary" disabled>停止</button>
    </div>
</div>

<script>
    // 环境切换开关：'dev' 开发环境（调用本地http接口），'prod' 生产环境（调用/api接口）
    const ENV_MODE = 'prod'; // 修改此值切换环境
    
    let es = null;          // 当前 EventSource 实例
    let currentResponseId = null; // 当前响应的消息ID
    const msgDiv = document.getElementById('msgDiv');
    const questionInput = document.getElementById('question');
    const sendBtn = document.getElementById('sendBtn');
    const stopBtn = document.getElementById('stopBtn');
    
    // 配置marked解析器
    marked.setOptions({
        breaks: true,
        gfm: true,
        headerIds: false,
        mangle: false
    });

    // 发送 + 接收
    function startSSE() {
        const q = questionInput.value.trim();
        if (!q) return;
        
        sendBtn.disabled = true;
        stopBtn.disabled = false;
        
        // 创建用户消息元素
        const userMessage = createUserMessage(q);
        msgDiv.appendChild(userMessage);
        
        // 清空输入框
        questionInput.value = '';
        
        // 创建系统消息容器（等待填充内容）
        currentResponseId = 'response-' + Date.now();
        const systemMessage = createSystemMessageContainer(currentResponseId);
        msgDiv.appendChild(systemMessage);
        
        // 滚动到底部
        scrollToBottom();

        // 1. 建立 SSE 连接，根据环境选择接口地址
        const sseUrl = ENV_MODE === 'dev' 
            ? `http://localhost:8181/ai/chat/sse/msg/1?content=${encodeURIComponent(q)}&role=user&model=deepseek` 
            : `/api/chat/sse/msg/1?content=${encodeURIComponent(q)}&role=user&model=deepseek`;
            
        es = new EventSource(sseUrl);

        // 2. 普通消息 → 实时渲染
        es.onmessage = e => {
            updateSystemMessage(currentResponseId, e.data);
        };

        // 3. 具名事件：后端主动通知结束
        es.addEventListener('end', e => {
            updateSystemMessage(currentResponseId, '\n\n---\n输出完毕');
            closeSSE();
        });

        // 4. 异常处理
        es.onerror = e => {
            console.error('SSE error', e);
            updateSystemMessage(currentResponseId, '\n\n<span class="error">连接异常，已停止接收</span>');
            closeSSE();
        };
    }

    // 创建用户消息元素
    function createUserMessage(content) {
        const wrapper = document.createElement('div');
        wrapper.className = 'message-wrapper user';
        
        const avatar = document.createElement('div');
        avatar.className = 'message-avatar user';
        avatar.textContent = '用';
        
        const messageContent = document.createElement('div');
        messageContent.className = 'message-content user';
        messageContent.textContent = content;
        
        wrapper.appendChild(avatar);
        wrapper.appendChild(messageContent);
        
        return wrapper;
    }

    // 创建系统消息容器
    function createSystemMessageContainer(id) {
        const wrapper = document.createElement('div');
        wrapper.className = 'message-wrapper system';
        wrapper.id = id;
        
        const avatar = document.createElement('div');
        avatar.className = 'message-avatar system';
        avatar.textContent = '智';
        
        const messageContent = document.createElement('div');
        messageContent.className = 'message-content system markdown-body';
        
        wrapper.appendChild(avatar);
        wrapper.appendChild(messageContent);
        
        return wrapper;
    }

    // 更新系统消息内容（带Markdown解析）
    function updateSystemMessage(id, content) {
        const messageWrapper = document.getElementById(id);
        if (!messageWrapper) return;
        
        const messageContent = messageWrapper.querySelector('.message-content');
        if (!messageContent) return;
        
        // 累积内容
        const currentContent = messageContent.getAttribute('data-original-content') || '';
        const newContent = currentContent + content;
        
        // 保存原始内容
        messageContent.setAttribute('data-original-content', newContent);
        
        // 解析Markdown并更新DOM
        try {
            messageContent.innerHTML = marked.parse(newContent);
        } catch (e) {
            console.error('Markdown解析错误:', e);
            messageContent.textContent = newContent;
        }
        
        // 滚动到底部
        scrollToBottom();
    }

    // 滚动到底部
    function scrollToBottom() {
        msgDiv.scrollTop = msgDiv.scrollHeight;
    }

    // 关闭连接
    function closeSSE() {
        if (es) {
            es.close();
            es = null;
        }
        sendBtn.disabled = false;
        stopBtn.disabled = true;
    }

    // 事件绑定
    sendBtn.addEventListener('click', startSSE);
    stopBtn.addEventListener('click', closeSSE);
    questionInput.addEventListener('keydown', e => {
        if (e.key === 'Enter') startSSE();
    });
</script>
</body>
</html>